import React, { useState } from 'react';
import PropTypes from 'prop-types';
import clsx from 'clsx';
import { makeStyles } from '@material-ui/core/styles';
import {
  Avatar,
  Typography,
  IconButton,
  Menu,
  MenuItem,
  Button,
  TextField,
  Dialog,
  DialogActions,
  DialogContent,
  DialogContentText,
  DialogTitle,
  RadioGroup,
  FormControlLabel,
  Radio,
  Grid
} from '@material-ui/core';
import MoreVertIcon from '@material-ui/icons/MoreVert';
import { useSelector, useDispatch } from 'react-redux';
import { setLoading } from 'redux/actions/LoadingActions';
import { setCallbackError } from 'redux/actions/LoadingActions';
import { CKEditor } from '@ckeditor/ckeditor5-react';
import ClassicEditor from '@ckeditor/ckeditor5-build-classic';
import ReactHtmlParser from 'react-html-parser';
import { callPostApi, callUploadFile } from 'utils/networking';
import { useHistory } from 'react-router-dom/cjs/react-router-dom.min';

const useStyles = makeStyles(theme => ({
  root: {
    width: '100%',
    height: '100%',
    position: 'relative',
    overflow: 'hidden',
  },
  yourComment: {
    width: '100%',
    marginTop: '20px',
    display: 'flex',
    flexDirection: 'row',
    justifyContent: 'space-between'
  },
  replyComment: {
    width: '100%',
    marginTop: '20px',
    marginLeft: '50px',
    paddingRight: '50px',
    display: 'flex',
    flexDirection: 'row',
    justifyContent: 'space-between'
  },
  avatarContainer: {
    display: 'flex',
    justifyContent: 'center',
    alignItems: 'center',
  },
  username: {
    marginLeft: '10px',
  },
  listItemComment: {
    marginTop: '10px',
    marginLeft: '10px',
    flex: '0 0 auto',
    marginRight: theme.spacing(2),
    whiteSpace: 'nowrap',
  },
  listItemText: {
    marginLeft: '10px',
    flex: '0 0 auto',
    marginRight: theme.spacing(2),
    whiteSpace: 'nowrap',
  },
  more: {
    display: 'flex',
    justifyContent: 'center',
    alignItems: 'center',
  },
  yourReply: {
    marginTop: '20px',
    marginLeft: '50px',
    display: 'flex',
    flexDirection: 'row',
    alignItems: 'start',
  },
  submitBtnContainer: {
    marginTop: '10px',
    width: '100%',
    display: 'flex',
    flexDirection: 'column',
    alignItems: 'end'
  },
  submitBtnSubContainer: {
    display: 'row',
  },
  replyCommentItem: {
    marginTop: '10px',
    marginLeft: '60px'
  }
}));

const Comment = props => {
  const { className, comment, deleted, ...rest } = props;
  const classes = useStyles();
  const dispatch = useDispatch();
  const history = useHistory();

  const profileData = useSelector((state) => state.auth.profileData)

  const [anchorEl, setAnchorEl] = useState(null);
  const [replyCommentID, setReplyCommentID] = useState('');
  const [replyComment, setReplyComment] = useState('');
  const [reply, setReply] = useState(false);
  const [replyType, setReplyType] = useState('reply');
  const [rComments, setRComments] = useState(comment.r_comments ? comment.r_comments : []);
  const [reportValue, setReportValue] = useState('content');

  const handleMenu = (event, commentID) => {
    setReplyCommentID(commentID);
    setAnchorEl(event.currentTarget);
  };

  const handleClose = () => {
    setAnchorEl(null);
  };

  const handleMenuItem = (type) => {
    handleClose()

    setReplyType(type);
    setReply(true);

    if (type == 'reply') {
      setReplyComment('');

    } else if (type == 'edit') {
      if (replyCommentID == comment.id) {
        setReplyComment(comment.comment);

      } else {
        console.log(rComments);
        for (let i = 0; i < rComments.length; i++) {
          let item = rComments[i];
          if (replyCommentID == item.id) {
            setReplyComment(item.comment);
            break;
          }
        }
      }
    }
  }

  const handleReportChange = (event) => {
    setReportValue(event.target.value);
  };

  const onChangeComment = (value) => {
    console.log(value);

    setReplyComment(value);
  }

  const cancelSubmit = () => {
    setReply(false);
  }

  const submitReplyComment = async () => {
    setReply(false);
    dispatch(setLoading(true));
    console.log(replyType)

    if (replyType == 'report') {
      const data = {
        user_id: profileData.id,
        subject: `Comment report - ID${replyCommentID}`,
        message: reportValue
      }
      callPostApi('user/contact_us', data, dispatch, (data) => {
        dispatch(setCallbackError({
          title: 'Success',
          content: 'Successfully submitted'
        }));
      })
    } 
    else if (replyType == 'delete') {
      const data = {
        user_id: profileData.id,
        comment_id: replyCommentID
      }
      callPostApi('blog/delete_comment', data, dispatch, (data) => {
        if (replyCommentID == comment.id) {
          deleted(comment.id);
        } 
        else {
          var urComments = [...rComments];
          for (let i = 0; i < urComments.length; i++) {
            let item = urComments[i];
            if (item.id == replyCommentID) {
              console.log('deleted');
              urComments.splice(i, 1);
              break;
            }
          }
          setRComments(urComments);
        }
      })
    } 
    else if (replyType == 'edit') {
      if (!replyComment) {
        dispatch(setCallbackError('Please add your comment'));
        return;
      }

      const data = {
        user_id: profileData.id,
        comment_id: replyCommentID,
        comment: replyComment,
      }
      callPostApi('blog/update_comment', data, dispatch, (data) => {
        setReplyComment('');
        var urComments = [...rComments];
        for (let i = 0; i < urComments.length; i++) {
          let item = urComments[i];
          if (item.id == replyCommentID) {
            urComments[i] = data;
            break;
          }
        }
        setRComments(urComments);
      })
    } 
    else if (replyType == 'reply') {
      if (!replyComment) {
        dispatch(setCallbackError('Please add your comment'));
        return;
      }

      const data = {
        user_id: profileData.id,
        blog_id: comment.blog_id,
        comment_id: comment.id,
        comment: replyComment,
      }
      callPostApi('blog/comment', data, dispatch, (data) => {
        setReplyComment('');
        var urComments = [...rComments];
        urComments.push(data);
        setRComments(urComments);
      })
    }
  }

  const getDialogTitle = () => {
    if (replyType == 'reply') {
      return 'Reply';
    } else if (replyType == 'report') {
      return 'Report Comment';
    } else if (replyType == 'edit') {
      return 'Edit your comment';
    } else if (replyType == 'delete') {
      return 'Delete Comment';
    }
    return 'Reply';
  }

  const getDialogDescription = () => {
    if (replyType == 'reply') {
      return 'Add your comment';
    } else if (replyType == 'report') {
      return 'Help us understand what is wrong with this comment';
    } else if (replyType == 'edit') {
      return 'Edit your comment';
    } else if (replyType == 'delete') {
      return 'Are you sure to delete the comment?';
    }
    return '';
  }

  function uploadAdapter(loader) {
    return {
      upload: () => {
        return new Promise((resolve, reject) => {
          loader.file.then((file) => {
            callUploadFile('blog/upload_comment_file', file, dispatch, (data) => {
              resolve({
                default: data
              }, (err) => {
                reject(err);
              });
            })
          });
        });
      }
    };
  }

  function uploadPlugin(editor) {
    editor.plugins.get("FileRepository").createUploadAdapter = (loader) => {
      return uploadAdapter(loader);
    };
  }

  const getDialogContent = () => {
    if (replyType == 'report') {
      return (
        <RadioGroup aria-label="gender" name="gender1" value={reportValue} onChange={handleReportChange}>
          <FormControlLabel value="content" control={<Radio />} label="Offensive Content" />
          <FormControlLabel value="media" control={<Radio />} label="Offensive Media" />
          <FormControlLabel value="spam" control={<Radio />} label="Spam" />
        </RadioGroup>
      )

    } else if (replyType == 'delete') {
      return (
        <div></div>
      )

    } else {
      return (
        <div style={{ flex: '1' }}>
          <CKEditor
            config={{
              extraPlugins: [uploadPlugin]
            }}
            editor={ClassicEditor}
            data={replyComment}
            onReady={editor => {
              // You can store the "editor" and use when it is needed.
              console.log('Editor is ready to use!', editor);
            }}
            onChange={(event, editor) => {
              const data = editor.getData();
              onChangeComment(data);
              console.log({ event, editor, data });
            }}
            onBlur={(event, editor) => {
              console.log('Blur.', editor);
            }}
            onFocus={(event, editor) => {
              console.log('Focus.', editor);
            }}
          />
        </div>
      )
      // return (<TextField
      //   autoFocus
      //   margin="dense"
      //   id="name"
      //   label="Write here"
      //   type="text"
      //   multiline
      //   value={replyComment}
      //   onChange={(e) => {
      //     onChangeComment(e.target.value);
      //   }}
      //   fullWidth
      // />);
    }

  }

  return (
    <div className={clsx(classes.root, className)} {...rest}>
      <div className={classes.yourComment}>
        <div className={classes.avatarContainer}>
          <Avatar {...{ src: comment.user.avatarURL }} className={classes.avatar} />
          <Typography variant="body2" color="textPrimary" className={clsx(classes.username, 'menu-item')}>
            {comment.user.username}
          </Typography>
        </div>
        <div className={classes.more}>
          <Typography variant="body2" color="textPrimary" className={clsx('menu-item')}>
            {comment.created_at}
          </Typography>
          <IconButton aria-label="more" onClick={e => {
            handleMenu(e, comment.id)
          }}>
            <MoreVertIcon />
          </IconButton>

          <Menu
            id="menu_add_media"
            anchorEl={anchorEl}
            anchorOrigin={{
              vertical: 'top',
              horizontal: 'right',
            }}
            getContentAnchorEl={null}
            keepMounted
            open={Boolean(anchorEl)}
            onClose={handleClose}
          >
            <MenuItem onClick={e => {
              e.stopPropagation()
              handleMenuItem('reply')
            }}>Reply</MenuItem>
            <MenuItem onClick={e => {
              e.stopPropagation()
              handleMenuItem('report')
            }}>Report</MenuItem>
            {profileData && comment.user.id == profileData.id && (
              <div>
                <MenuItem onClick={e => {
                  e.stopPropagation()
                  handleMenuItem('edit')
                }}>Edit</MenuItem>
                <MenuItem onClick={e => {
                  e.stopPropagation()
                  handleMenuItem('delete')
                }}>Delete</MenuItem>
              </div>
            )}

          </Menu>
        </div>
      </div>
      <div variant="body2" color="textPrimary" className={clsx(classes.listItemComment, 'menu-item')}>
        {ReactHtmlParser(comment.comment)}
      </div>

      {rComments.map((item, index) => (
        <Grid key={index}>
          <div className={classes.replyComment}>
            <div className={classes.avatarContainer}>
              <Avatar {...{ src: item.user.avatarURL }} className={classes.avatar} />
              <Typography variant="body2" color="textPrimary" className={clsx(classes.username, 'menu-item')}>
                {item.user.username}
              </Typography>
            </div>
            <div className={classes.more}>
              <Typography variant="body2" color="textPrimary" className={clsx('menu-item')}>
                {item.created_at}
              </Typography>
              <IconButton aria-label="more" onClick={e => {
                handleMenu(e, item.id)
              }}>
                <MoreVertIcon />
              </IconButton>
            </div>
          </div>
          <div variant="body2" color="textPrimary" className={clsx(classes.replyCommentItem, 'menu-item')}>
            {ReactHtmlParser(item.comment)}
          </div>
        </Grid>
      ))}

      <Dialog open={reply} onClose={cancelSubmit} aria-labelledby="form-dialog-title"
        fullWidth
        maxWidth="md">
        <DialogTitle id="form-dialog-title">
          {getDialogTitle()}
        </DialogTitle>
        <DialogContent>
          <DialogContentText>
            {getDialogDescription()}
          </DialogContentText>
          {getDialogContent()}
        </DialogContent>
        <DialogActions>
          <Button onClick={handleClose} color="primary" onClick={cancelSubmit}>
            Cancel
          </Button>
          <Button onClick={handleClose} color="primary" style={{ marginRight: '7px' }} onClick={submitReplyComment}>
            Submit
          </Button>
        </DialogActions>
      </Dialog>

    </div>
  );
};

Comment.propTypes = {
  /**
   * External classes
   */
  className: PropTypes.string,
  /**
   * data of the comment
   */
  comment: PropTypes.object,
  deleted: PropTypes.func
};

export default Comment;
